var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

//设置跨域访问
app.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();  
});  

//引入数据库模块
var Message = require('./index.js');

//查找所有留言
app.get('/', function(req, res, next) {
    console.log('dsdsajd');
    Message.findAll().then(function(msgs) {
        console.log('msg is: ' + msgs);
        res.send({ messages: msgs });
    });
});

//删除一个留言
app.get('/del_msg', function(req, res, next) {
    //如果没有id字段,返回404
    if (req.query.id == undefined ||req.query.id == '') {
        res.render('error', {});
        return;
    }
    //先查找,再调用删除,最后返回首页
    Message.findOne({
        where:{
            id:req.query.id
        }
    }).then(function(msg){
        msg.destroy().then(function(){
            console.log('delete success !!');
            res.redirect('/');
        });
    });
});

//添加一条留言
app.post('/add_msg', function(req, res, next) {
    //如果没有post数据或者数据为空,直接返回
    console.log(req.body);
    if (req.body.username == undefined ||req.body.username == ''
        || req.body.content == undefined || req.body.content == '') {
        res.send({message:'lost required params'});
        return;
    }
    var message = {
        username: req.body.username,
        content: req.body.content
    };
    //创建一条记录,创建成功后跳转回首页
    Message.create(message).then(function(msg){
        console.log(msg);
        res.redirect('/');
    }, function(msg){
        console.log(msg);
    });
});
console.log('server running at 9900');
// module.exports = router;
app.listen(9900);